<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="字典类型" name="type">
        <!-- 字典类型工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAddType">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              :disabled="typeSelection.length === 0"
              icon="Delete"
              @click="handleBatchDeleteType"
            >批量删除</el-button>
          </el-col>
        </el-row>

        <!-- 字典类型搜索栏 -->
        <el-form :model="typeQuery" ref="typeQueryRef" :inline="true">
          <el-form-item label="字典名称" prop="dictName">
            <el-input
              v-model="typeQuery.dictName"
              placeholder="请输入字典名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQueryType"
            />
          </el-form-item>
          <el-form-item label="字典类型" prop="dictType">
            <el-input
              v-model="typeQuery.dictType"
              placeholder="请输入字典类型"
              clearable
              style="width: 240px"
              @keyup.enter="handleQueryType"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="typeQuery.status" placeholder="字典状态" clearable style="width: 240px">
              <el-option value="1" label="正常" />
              <el-option value="0" label="停用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQueryType">搜索</el-button>
            <el-button icon="Refresh" @click="resetTypeQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 字典类型表格 -->
        <el-table
          :data="typeList"
          @selection-change="handleTypeSelectionChange"
          @row-click="handleTypeRowClick"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="字典编号" prop="dictId"/>
          <el-table-column label="字典名称" prop="dictName" :show-overflow-tooltip="true"/>
          <el-table-column label="字典类型" prop="dictType" :show-overflow-tooltip="true"/>
          <el-table-column label="状态" prop="status" >
            <template #default="scope">
              <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
              <el-tag v-else type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" prop="createTime"/>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <div class="operation-links">
                <el-button type="text" icon="View" @click.stop="handleDictData(scope.row)">数据</el-button>
                <el-button link type="primary" icon="Edit" @click.stop="handleUpdateType(scope.row)">编辑</el-button>
                <el-popconfirm title="确定删除吗？" @confirm="handleDeleteType(scope.row, $event)">
                  <template #reference>
                    <el-button link type="danger" icon="Delete" @click.stop>删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="字典数据" name="data" :disabled="!currentDictType">
        <!-- 字典数据工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAddData">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              :disabled="dataSelection.length === 0"
              icon="Delete"
              @click="handleBatchDeleteData"
            >批量删除</el-button>
          </el-col>
          <el-col :span="4">
            <el-tag type="info">当前字典类型: {{ currentDictType }}</el-tag>
          </el-col>
        </el-row>

        <!-- 字典数据搜索栏 -->
        <el-form :model="dataQuery" ref="dataQueryRef" :inline="true">
          <el-form-item label="字典标签" prop="dictLabel">
            <el-input
              v-model="dataQuery.dictLabel"
              placeholder="请输入字典标签"
              clearable
              style="width: 240px"
              @keyup.enter="handleQueryData"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="dataQuery.status" placeholder="数据状态" clearable style="width: 240px">
              <el-option value="1" label="正常" />
              <el-option value="0" label="停用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQueryData">搜索</el-button>
            <el-button icon="Refresh" @click="resetDataQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 字典数据表格 -->
        <el-table
          :data="dataList"
          @selection-change="handleDataSelectionChange"
          @row-click="handleDataRowClick"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="字典编码" prop="dictCode"/>
          <el-table-column label="字典标签" prop="dictLabel" :show-overflow-tooltip="true" />
          <el-table-column label="字典键值" prop="dictValue" :show-overflow-tooltip="true" />
          <el-table-column label="字典排序" prop="dictSort"/>
          <el-table-column label="样式类型" prop="listClass" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-tag v-if="scope.row.listClass" :type="scope.row.listClass">{{ scope.row.listClass }}</el-tag>
              <span v-else>默认</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" >
            <template #default="scope">
              <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
              <el-tag v-else type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column label="创建时间" prop="createTime"/>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <div class="operation-links">
                <el-button link type="primary" icon="Edit" @click.stop="handleUpdateData(scope.row)">编辑</el-button>
                <el-popconfirm title="确定删除吗？" @confirm="handleDeleteData(scope.row, $event)">
                  <template #reference>
                    <el-button link type="danger" icon="Delete" @click.stop>删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 字典类型对话框 -->
    <el-dialog :title="typeDialogTitle" v-model="typeDialogVisible" width="600px" append-to-body>
      <el-form ref="typeFormRef" :model="typeForm" :rules="typeRules" label-width="100px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="typeForm.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="typeForm.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="typeForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="typeForm.remark" type="textarea" :rows="3" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTypeForm">确 定</el-button>
          <el-button @click="cancelTypeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 字典数据对话框 -->
    <el-dialog :title="dataDialogTitle" v-model="dataDialogVisible" width="600px" append-to-body>
      <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px">
        <el-form-item label="字典类型">
          <el-input v-model="dataForm.dictType" disabled />
        </el-form-item>
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="dataForm.dictLabel" placeholder="请输入字典标签" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="dataForm.dictValue" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="字典排序" prop="dictSort">
          <el-input-number v-model="dataForm.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="样式类型" prop="listClass">
          <el-select v-model="dataForm.listClass" placeholder="请选择样式类型">
            <template #prefix>
              <el-tag v-if="dataForm.listClass" :type="dataForm.listClass" style="margin-right: 8px;">
                {{ listClassOptions.find(item => item.value === dataForm.listClass)?.label || dataForm.listClass }}
              </el-tag>
            </template>
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <div style="display: flex; align-items: center;">
                <el-tag v-if="item.value" :type="item.value" style="margin-right: 8px;">{{ item.label }}</el-tag>
                <span v-else>{{ item.label }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <el-radio-group v-model="dataForm.isDefault">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark" type="textarea" :rows="3" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataForm">确 定</el-button>
          <el-button @click="cancelDataDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  getType,
  addType,
  updateType,
  delType,
  batchDeleteType,
  listData,
  getData,
  addData,
  updateData,
  delData,
  batchDeleteData
} from '@/api/dict'

export default {
  name: "DictView",
  data() {
    return {
      activeName: 'type',// 选中tab
      typeQuery: {},// 字典类型查询条件
      dataQuery: {},// 字典数据查询条件
      typeList: [], // 字典类型列表
      dataList: [], // 字典数据列表
      typeSelection: [],// 字典类型选中数据
      dataSelection: [],// 字典数据选中数据
      currentDictType: '',// 当前选中的字典类型
      currentDictName: '',// 当前选中的字典数据类型名称
      typeDialogVisible: false,// 字典类型弹窗
      typeDialogTitle: '', // 字典类型弹窗标题
      dataDialogVisible: false, // 字典数据弹窗
      dataDialogTitle: '', //字典数据弹窗标题
      typeForm: {// 字典类型表单
        status: 1,
      },
      dataForm: {// 字典数据表单
        dictSort: 0,
        isDefault: 0,
        status: 1,
      },
      typeRules: {// 字典类型表单校验
        dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
        dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }]
      },
      dataRules: {// 字典数据表单校验
        dictLabel: [{ required: true, message: '字典标签不能为空', trigger: 'blur' }],
        dictValue: [{ required: true, message: '字典键值不能为空', trigger: 'blur' }],
        dictSort: [{ required: true, message: '字典排序不能为空', trigger: 'blur' }]
      },
      listClassOptions: [// 样式类型选项
        { value: '', label: '默认' },
        { value: 'primary', label: '主要' },
        { value: 'success', label: '成功' },
        { value: 'info', label: '信息' },
        { value: 'warning', label: '警告' },
        { value: 'danger', label: '危险' }
      ]
    };
  },
  created() {
    this.getTypeList();

    // 添加ResizeObserver错误捕获
    window.addEventListener('error', (e) => {
      if (e && e.message && (
          e.message === 'ResizeObserver loop limit exceeded' ||
          e.message.includes('ResizeObserver loop completed with undelivered notifications')
      )) {
        const resizeObserverErr = e;
        resizeObserverErr.stopImmediatePropagation();
      }
    }, true);
  },
  methods: {
    handleTabClick() {// 切换标签页
      if (this.activeName === 'type') {
        this.getTypeList();
      } else if (this.activeName === 'data') {
        this.getDataList();
      }
    },
    getTypeList() {// 获取字典类型列表
      listType(this.typeQuery).then(response => {
        if (response.code === 200) {
          this.typeList = response.data;
          return;
        }
        this.$message.error('获取字典类型列表失败');
    })
    },
    // 获取字典数据列表
    getDataList() {
      if (!this.currentDictType) {
        return;
      }
      this.dataQuery.dictType = this.currentDictType;
      listData(this.dataQuery).then(response => {
        if (response.code === 200) {
          this.dataList = response.data;
          return;
        }
        this.$message.error('获取字典数据列表失败');
      });
    },
    // 字典类型查询
    handleQueryType() {
      this.getTypeList();
    },
    // 字典数据查询
    handleQueryData() {
      this.getDataList();
    },
    // 重置字典类型查询
    resetTypeQuery() {
      this.typeQuery = {};
      this.getTypeList();
    },
    // 重置字典数据查询
    resetDataQuery() {
      this.dataQuery = {
        dictType: this.currentDictType
      };
      this.getDataList();
    },
    // 字典类型选择状态改变
    handleTypeSelectionChange(selection) {
      this.typeSelection = selection;
    },
    // 字典数据选择状态改变
    handleDataSelectionChange(selection) {
      this.dataSelection = selection;
    },
    // 点击行显示字典数据
    handleTypeRowClick(row) {
      this.currentDictType = row.dictType;
      this.currentDictName = row.dictName;
      this.activeName = 'data';
      this.getDataList();
    },
    // 点击行显示字典类型
    handleDataRowClick(row) {
      this.activeName = 'type';
      this.getTypeList();
    },
    // 显示字典数据
    handleDictData(row) {
      this.currentDictType = row.dictType;
      this.currentDictName = row.dictName;
      this.activeName = 'data';
      this.getDataList(); 
    },
    // 新增字典类型
    handleAddType() {
      this.typeDialogTitle = '添加字典类型';
      this.typeDialogVisible = true;
      this.resetTypeForm();
    },
    // 修改字典类型
    handleUpdateType(row) {
      this.typeDialogTitle = '修改字典类型';
      this.typeDialogVisible = true;
      this.resetTypeForm();
      getType(row.dictId).then(response => {
        if (response.code === 200) {
          this.typeForm = response.data;
          return;
        }
        this.$message.error('获取字典类型信息失败');
      });
    },
    // 删除字典类型
    handleDeleteType(row, event) {
        if (event) {
          event.stopPropagation();
        }
        delType(row.dictId).then(() => {
          this.$message.success('删除成功');
          this.getTypeList();
        });
    },
    // 批量删除字典类型
    handleBatchDeleteType() {
      const dictIds = this.typeSelection.map(item => item.dictId);
      this.$confirm('是否确认删除选中的' + dictIds.length + '个字典类型?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDeleteType(dictIds.join(',')).then(() => {
          this.$message.success('批量删除成功');
          this.getTypeList();
        });
      }).catch(() => {});
    },
    // 新增字典数据
    handleAddData() {
      this.dataDialogTitle = '添加字典数据';
      this.dataDialogVisible = true;
      this.resetDataForm();
      this.dataForm.dictType = this.currentDictType;
    },
    // 修改字典数据
    handleUpdateData(row) {
      this.dataDialogTitle = '修改字典数据';
      this.dataDialogVisible = true;
      this.resetDataForm();
      getData(row.dictCode).then(response => {
        if (response.code === 200) {
          this.dataForm = response.data;
        } else {
          this.$message.error('获取字典数据信息失败');
        }
      });
    },
    // 删除字典数据
    handleDeleteData(row, event) {
      if (event) {
        event.stopPropagation();
      }
      delData(row.dictCode).then(() => {
        this.$message.success('删除成功');
        this.getDataList();
      });
    },
    // 批量删除字典数据
    handleBatchDeleteData() {
      const dictCodes = this.dataSelection.map(item => item.dictCode);
      this.$confirm('是否确认删除选中的' + dictCodes.length + '个字典数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDeleteData(dictCodes.join(',')).then(() => {
          this.$message.success('批量删除成功');
          this.getDataList();
        });
      }).catch(() => {});
    },
    // 提交字典类型表单
    submitTypeForm() {
      this.$refs.typeFormRef.validate(valid => {
        if (valid) {
          if (this.typeForm.dictId !== undefined) {
            updateType(this.typeForm).then(response => {
              if (response.code === 200) {
                this.$message.success('修改成功');
                this.typeDialogVisible = false;
                this.getTypeList();
              } else {
                this.$message.error('修改失败');
              }
            });
          } else {
            addType(this.typeForm).then(response => {
              if (response.code === 200) {
                this.$message.success('新增成功');
                this.typeDialogVisible = false;
                this.getTypeList();
              } else {
                this.$message.error('新增失败');
              }
            });
          }
        }
      });
    },
    // 提交字典数据表单
    submitDataForm() {
      this.$refs.dataFormRef.validate(valid => {
        if (valid) {
          if (this.dataForm.dictCode !== undefined) {
            updateData(this.dataForm).then(response => {
              if (response.code === 200) {
                this.$message.success('修改成功');
                this.dataDialogVisible = false;
                this.getDataList();
              } else {
                this.$message.error('修改失败');
              }
            });
          } else {
            addData(this.dataForm).then(response => {
              if (response.code === 200) {
                this.$message.success('新增成功');
                this.dataDialogVisible = false;
                this.getDataList();
              } else {
                this.$message.error('新增失败');
              }
            });
          }
        }
      });
    },
    // 取消字典类型表单
    cancelTypeDialog() {
      this.typeDialogVisible = false;
    },
    // 取消字典数据表单
    cancelDataDialog() {
      this.dataDialogVisible = false;
    },
    // 重置字典类型表单
    resetTypeForm() {
      this.typeForm = {
        status: 1,
      };
      this.$refs["typeFormRef"] && this.$refs["typeFormRef"].resetFields();
    },
    // 重置字典数据表单
    resetDataForm() {
      this.dataForm = {
        dictType: this.currentDictType,
        dictSort: 0,
        isDefault: 0,
        status: 1,
      };
      this.$refs["dataFormRef"] && this.$refs["dataFormRef"].resetFields();
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
